import { BaseEditor } from './BaseEditor'
import { CellValue } from '../types'

export class CheckboxEditor extends BaseEditor {
  protected checkbox: HTMLInputElement | null = null
  protected wrapper: HTMLDivElement | null = null
  
  protected createElement(value: CellValue): HTMLElement {
    const editOptions = this.getEditOptions()
    
    // 创建包装器
    this.wrapper = document.createElement('div')
    this.wrapper.style.cssText = `
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
    `
    
    // 创建复选框
    this.checkbox = document.createElement('input')
    this.checkbox.type = 'checkbox'
    
    // 设置属性
    if (editOptions.readonly) {
      this.checkbox.disabled = true
    }
    
    // 设置初始值
    this.setValue(value)
    
    // 添加标签（如果有）
    if (editOptions.label) {
      const label = document.createElement('label')
      label.style.cssText = `
        display: flex;
        align-items: center;
        gap: 8px;
        cursor: pointer;
      `
      label.appendChild(this.checkbox)
      label.appendChild(document.createTextNode(editOptions.label))
      this.wrapper.appendChild(label)
    } else {
      this.wrapper.appendChild(this.checkbox)
    }
    
    return this.wrapper
  }
  
  getValue(): CellValue {
    if (!this.checkbox) return false
    return this.checkbox.checked
  }
  
  setValue(value: CellValue): void {
    if (!this.checkbox) return
    this.checkbox.checked = !!value
  }
  
  protected applyStyles(): void {
    // 复选框使用包装器的样式，不需要基类的边框样式
    if (!this.wrapper) return
    
    this.wrapper.style.cssText = `
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      background: white;
      border: 2px solid #3b82f6;
      border-radius: 4px;
    `
  }
  
  protected applyCustomStyles(): void {
    if (!this.checkbox) return
    
    // 复选框的特殊样式
    this.checkbox.style.cssText = `
      width: 18px;
      height: 18px;
      cursor: pointer;
    `
  }
  
  focus(): void {
    if (this.checkbox) {
      this.checkbox.focus()
    }
  }
  
  protected attachCustomEventListeners(): void {
    if (!this.checkbox) return
    
    // 监听变化事件
    this.checkbox.addEventListener('change', this.handleInput.bind(this))
    
    // 空格键切换
    this.checkbox.addEventListener('keydown', (e) => {
      if (e.key === ' ') {
        e.preventDefault()
        this.checkbox!.checked = !this.checkbox!.checked
        this.handleInput(e)
      }
    })
  }
} 